/*
 * tim5.c
 *
 *  Created on: Jul 3, 2024
 *      Author: 23206
 */

#include "tim5.h"
#include <stdio.h>
//PA0 AF2
void TIM5_CH1_Config(void)
{
	RCC->AHB1ENR |= 1<<0;

	GPIOA->MODER &= ~(0x3<<2*0);
	GPIOA->MODER |=  (0x2<<2*0);

	GPIOA->AFR[0] &= ~(0xF<<4*0);
	GPIOA->AFR[0] |=  (0x2<<4*0);

	TIM5_Config();
}

void TIM5_Config(void)
{
    //1.开时钟
	RCC->APB1ENR |= 1<<3;
	//2.时基单元
	TIM5->CNT = 0;
	TIM5->PSC = 8400-1;
	TIM5->ARR = 50000-1;  //5S

	TIM5->CR1 |=  (1<<7);
	TIM5->CR1 &= ~((1<<3)|(1<<2)|(1<<1));


	TIM5->EGR |=  (1<<0);  //软件触发影子寄存器
	TIM5->SR  &= ~(1<<0);

	//输入配置

	TIM5->CCMR1 &= ~(0xFF<<0);
	TIM5->CCMR1 |=  (0x01<<0);

	TIM5->CCER  &= ~(0xF<<0);
	TIM5->CCER  |= (1<<3);
	TIM5->CCER  |= (1<<1);//11
	TIM5->CCER  |= (1<<0);//允许捕获

    TIM5->DIER |= 1<<0; //溢出中断
    TIM5->DIER |= 1<<1; //捕获中断


//    NVIC_SetPriority(TIM5_IRQn, NVIC_EncodePriority(7-2,1,3));
//    NVIC_EnableIRQ(TIM5_IRQn); //使能某个编号的中断



	NVIC_InitTypeDef NVIC_InitStruct;//定义一个结构体变量

	NVIC_InitStruct.NVIC_IRQChannel                   = TIM5_IRQn;//通道号
	NVIC_InitStruct.NVIC_IRQChannelCmd                = ENABLE;     //是否使能
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;          //抢占优先级
	NVIC_InitStruct.NVIC_IRQChannelSubPriority        = 3;          //次级优先级

	NVIC_Init(&NVIC_InitStruct);//结构体变量的地址

	TIM5->CR1 |= 1<<0;
}


//中断服务函数的特点
void TIM5_IRQHandler(void)
{
	float  Time = 0.0;
	static uint8_t Over_Cnt;
	static uint16_t Time1;
	static uint16_t Time2;
	//1.判断标志位
	if(TIM5->SR & 1<<0)
	{
		//2.清除标志
		TIM5->SR &= ~(1<<0);
//		printf("TIM5 5S IS OK\r\n");
		Over_Cnt++;
	}
	if(TIM5->SR & 1<<1)
	{
		TIM5->SR &= ~(1<<1);
		if(GPIOA->IDR & 1<<0)
		{
			Over_Cnt = 0;
			Time1 = TIM5->CCR1;
			printf("TIM5_CCR1 = %d\r\n",TIM5->CCR1);
			printf("Capture is ok UP Edge\r\n");
			printf("TIM5_CNT = %d\r\n",TIM5->CNT);
		}
		else
		{
			Time2 = TIM5->CCR1;
			Time = (Over_Cnt * 50000+ Time2 - Time1)*0.1;//ms
			printf("Press Time is %f ms\r\n",Time);
//			printf("TIM5_CCR1 = %d\r\n",TIM5->CCR1);
//			printf("Capture is ok Down Edge\r\n");
//			printf("TIM5_CNT = %d\r\n",TIM5->CNT);
		}
	}
}
